package com.sharding;


import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.SqlUtil;
import com.jiao.comm.utils.JDBCUtils;
import com.jiao.table.jdbc.SQLBuilder;
import com.sharding.entity.Person;
import com.sharding.mapper.PersonMapper;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: vincent.jiao
 * @Date: 2021/6/14
 */
public class MyDemo {
    public static void main(String[] arsg) throws ClassNotFoundException, SQLException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException {
        Class.forName("com.mysql.jdbc.Driver");

        //获取数据库连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jiao?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull"
                , "root" , "123456");


        demo6(conn, Person.class);
    }

    private static <T> List<T> demo6(Connection conn, Class clazz) throws NoSuchFieldException, IllegalAccessException {

        String sql = SQLBuilder.getSelectAllSql("person");
        List<T> datas = new LinkedList<>();
        try(
                ResultSet rs  = JDBCUtils.select(conn, sql);
        ) {

            ResultSetMetaData metaData = rs.getMetaData();
            while (rs.next()){
                T t = (T) clazz.newInstance();

                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String colName = metaData.getColumnName(i);
                    Field field = clazz.getDeclaredField(colName);
                    Class fieldType = field.getType();
                    field.setAccessible(true);

                    if(Integer.class.equals(fieldType)) {
                        field.set(rs.getInt(colName), t);
                    } else if(Date.class.equals(fieldType)) {
                        field.set(rs.getDate(colName), t);
                    } else if(Timestamp.class.equals(fieldType)) {
                        field.set(rs.getTimestamp(colName), t);
                    } else if(Long.class.equals(fieldType)) {
                        long val = rs.getLong(colName);

                        Field field2 = Person.class.getDeclaredField("p_id");
                        Person person = new Person();
                        field2.setAccessible(true);
                        field2.set(person, 5L);

                        field.set(val, t);



                    } else if(Short.class.equals(fieldType)) {
                        field.set(rs.getShort(colName), t);
                    } else if(Byte.class.equals(fieldType)) {
                        field.set(rs.getByte(colName), t);
                    } else if(Character.class.equals(fieldType)) {
                        String val = rs.getString(colName);
                        field.set(StrUtil.isEmpty(val) ? null : val.charAt(0), t);
                    } else if(String.class.equals(fieldType)) {
                        int sqlTypeNum = metaData.getColumnType(i);
                        if(sqlTypeNum == 2005) {        // CLOB
                            SqlUtil.clobToStr(rs.getClob(colName));
                        } else {
                            field.set(rs.getString(colName), t);
                        }

                    } else if(Float.class.equals(fieldType)) {
                        field.set(rs.getInt(colName), t);
                    } else if(Double.class.equals(fieldType)) {
                        field.set(rs.getInt(colName), t);
                    } else if(Boolean.class.equals(fieldType)) {
                        field.set(rs.getInt(colName), t);
                    } else if(Clob.class.equals(fieldType)) {
                        field.set(rs.getClob(colName), t);
                    } else if(Blob.class.equals(fieldType)) {
                        field.set(rs.getBlob(colName), t);
                    }
                }

                datas.add(t);
            }

        } catch (SQLException | InstantiationException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }

        return datas;
    }

    private static void demo5() throws NoSuchMethodException {
        Object a = PersonMapper.class.getMethods();
        System.out.println(a);
    }

    private static void demo2(Connection conn)  throws ClassNotFoundException, SQLException{
        //使用Connection来创建一个Statment对象
        PreparedStatement stmt = conn.prepareStatement(" insert into users(name) values ( 'jiao2' ), ( 'jiao3' ), ( 'jiao4' ) ",
                Statement.RETURN_GENERATED_KEYS);
        //执行SQL,返回boolean值表示是否包含ResultSet
        stmt.executeUpdate();

        ResultSet rs = stmt.getGeneratedKeys();
        while (rs.next()) {
            System.out.println(rs.getObject(1));
        }
        rs.close();
        conn.close();
    }

    private static void demo3(Connection conn)  throws ClassNotFoundException, SQLException{
        //使用Connection来创建一个Statment对象
        PreparedStatement stmt = conn.prepareStatement(" insert into users(name) values ( 'jiao2' ), ( 'jiao3' ), ( 'jiao4' ) ",
                Statement.RETURN_GENERATED_KEYS);

        Statement statement = conn.createStatement();
        statement.addBatch("");
        statement.addBatch("");
        statement.addBatch("");

        conn.close();
    }

    private static void demo4(Connection conn)  throws ClassNotFoundException, SQLException{
        //使用Connection来创建一个Statment对象
        PreparedStatement stmt = conn.prepareStatement(" update aeitem set itm_title = 'jiao1' where itm_id = 1;" +
                        " update aeitem set itm_title = 'jiao2' where itm_id = 2; ",
                Statement.RETURN_GENERATED_KEYS);

        stmt.execute();
        System.out.println(stmt.getUpdateCount());
        conn.close();
    }

    private void demo1(Connection conn)  throws ClassNotFoundException, SQLException{
        //使用Connection来创建一个Statment对象
        Statement stmt = conn.createStatement();
        //执行SQL,返回boolean值表示是否包含ResultSet
        boolean hasResultSet = stmt.execute(" insert into users(name) values ( 'jiao1' ) ");
        //如果执行后有ResultSet结果集

        if (hasResultSet) {
            //获取结果集
            ResultSet rs = stmt.getResultSet();

            //ResultSetMetaData是用于分析结果集的元数据接口
            ResultSetMetaData rsmd = rs.getMetaData();

            int columnCount = rsmd.getColumnCount();
            //迭代输出ResultSet对象

            while (rs.next()) {
                //依次输出每列的值
                for (int i = 0 ; i < columnCount ; i++ ) {
                    System.out.print(rs.getString(i + 1) + "/t");
                }

                System.out.println("/n");
            }
        } else {
            System.out.println("该SQL语句影响的记录有" + stmt.getUpdateCount() + "条");
        }
    }
}
